package com.mlc.utils.commom;

import lombok.Data;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

/**
 * @author FireWang
 * @date 2020/11/11 10:32
 * 翻页工具
 */
@Data
public class PageUtil {

    /**
     * 当前页面序号
     */
    private Integer pageNumber = 1;

    /**
     * 页面展示条数
     */
    private Integer pageSize = 100;

    /**
     * 最大页数
     */
    private Integer maxPage = 1;

    /**
     * 最大条数
     */
    private Integer columns = 0;

    /**
     * sql查询条件:limit
     */
    private Integer limit = 100;

    /**
     * sql查询条件:offset
     */
    private Integer offset = 0;

    /**
     * jpa查询条件体
     */
    private Pageable pageable;


    /**
     * 格式化页面构方法：构造页数
     *
     * @param pageNumber
     * @param pageSize
     * @param columns
     * @return
     */
    public PageUtil(Integer pageNumber, Integer pageSize, Integer columns) {
        new PageUtil(pageNumber, pageSize);
        if (ConvUtil.convToInt(columns) > 0) {
            this.setColumns(columns);
            this.setMaxPage((int) Math.ceil(columns / (double) this.pageSize));
        }
    }

    /**
     * 格式化页面构方法：构造pageable
     *
     * @param pageNumber
     * @param pageSize
     * @return
     */
    public PageUtil(Integer pageNumber, Integer pageSize) {
        if (ConvUtil.convToInt(pageNumber) > 0) {
            this.pageNumber = pageNumber;
        }
        if (ConvUtil.convToInt(pageSize) > 0) {
            this.pageSize = pageSize;
            this.limit = pageSize;
            this.offset = pageSize * (pageNumber - 1);
            this.pageable = PageRequest.of(pageNumber - 1, pageSize);
        }
    }

    /**
     * 设置排序字段
     *
     * @param pageNumber
     * @param pageSize
     * @param orderString
     * @param orderType
     * @return
     */
    public PageUtil(Integer pageNumber, Integer pageSize, String orderString, Integer orderType) {
        if (ConvUtil.convToInt(pageNumber) > 0) {
            this.pageNumber = pageNumber;
        }
        if (ConvUtil.convToInt(pageSize) > 0) {
            this.pageSize = pageSize;
            this.limit = pageSize;
            this.offset = pageSize * (pageNumber - 1);
            if (ConvUtil.convToInt(orderType) == 0) {
                this.pageable = PageRequest.of(pageNumber - 1, pageSize, Sort.by(Sort.Direction.ASC, orderString));
            } else {
                this.pageable = PageRequest.of(pageNumber - 1, pageSize, Sort.by(Sort.Direction.DESC, orderString));
            }
        }
    }
}

